package com.live.luowang.MusicServie;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.os.SystemClock;
import android.support.v4.media.MediaBrowserCompat;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.format.DateUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.live.luowang.Adapter.MusicListViewAdapter;
import com.live.luowang.MyApplication;
import com.live.luowang.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.wingjay.blurimageviewlib.FastBlurUtil;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

public class MusicPlayingActivity extends AppCompatActivity implements View.OnClickListener {
    @Bind(R.id.background_image)
    ImageView backgroundImage;
    @Bind(R.id.PlayerName)
    TextView playerName;
    @Bind(R.id.PlayerArtist)
    TextView playerArtist;
    @Bind(R.id.PlayerImg)
    CircleImageView playerImg;
    @Bind(R.id.ControllerCurrent)
    TextView controllerCurrent;
    @Bind(R.id.ControllerSeekBar)
    SeekBar controllerSeekBar;
    @Bind(R.id.ControllerDuration)
    TextView controllerDuration;
    @Bind(R.id.ControllerPlay)
    ImageView controllerPlay;
    @Bind(R.id.ControllerPre)
    ImageView controllerPre;
    @Bind(R.id.ControllerNext)
    ImageView controllerNext;
    @Bind(R.id.ControllerList)
    ImageView controllerList;
    @Bind(R.id.ControllerNormal)
    ImageView normal;
    @Bind(R.id.ControllerLoop)
    ImageView loop;
    @Bind(R.id.ControllerShuffle)
    ImageView shuffle;
    @Bind(R.id.PreArrow)
    ImageView preArrow;
    @Bind(R.id.ControllerDisk)
    RelativeLayout controllerDisk;
    private MediaBrowserCompat mediaBrowser;
    private PlaybackStateCompat stateCompat;
    private final ScheduledExecutorService mExecutorService = Executors.newSingleThreadScheduledExecutor();
    private ScheduledFuture<?> mScheduleFuture;
    private SharedPreferences sp;
    private int duration;
    private MusicListViewAdapter adapter;
    private MusicProvider musicProvider;
    private boolean isStart=false;
    private boolean THREAD=true;
    private Thread thread;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        musicProvider = new MusicProvider();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4 全透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
        setContentView(R.layout.activity_music_playing_layout);
        ButterKnife.bind(this);
        sp = getSharedPreferences("playMode", MODE_PRIVATE);
        mediaBrowser = new MediaBrowserCompat(this, new ComponentName(this, MusicService.class), connectionCallback, null);
        if (sp.getBoolean("shuffle", false)) {
            shuffle.setVisibility(View.VISIBLE);
            normal.setVisibility(View.GONE);
            loop.setVisibility(View.GONE);
        } else if (sp.getBoolean("loop", false)) {
            shuffle.setVisibility(View.GONE);
            normal.setVisibility(View.GONE);
            loop.setVisibility(View.VISIBLE);
        }
        controllerSeekBar.setMax(MyApplication.getInstance().getDuration());
        controllerDuration.setText(DateUtils.formatElapsedTime(Long.valueOf(MyApplication.getInstance().getDuration()) / 1000));
        registerReceiver(durationReceiver, new IntentFilter("duration"));
        setListener();
        thread=new Thread(new CircleThread());
    }

    BroadcastReceiver durationReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            duration = intent.getIntExtra("duration", 0);
            MyApplication.getInstance().setDuration(duration);
            controllerSeekBar.setMax(duration);
            controllerDuration.setText(DateUtils.formatElapsedTime(Long.valueOf(duration) / 1000));
//            scheduleSeekbarUpdate();
        }
    };
    private final MediaBrowserCompat.ConnectionCallback connectionCallback = new MediaBrowserCompat.ConnectionCallback() {
        @Override
        public void onConnected() {
            MediaControllerCompat mediaController = null;
            try {
                mediaController = new MediaControllerCompat(MusicPlayingActivity.this, mediaBrowser.getSessionToken());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            setSupportMediaController(mediaController);
            mediaController.registerCallback(mCallback);
            mediaController.getTransportControls().play();
        }

        @Override
        public void onConnectionSuspended() {
            super.onConnectionSuspended();
        }

        @Override
        public void onConnectionFailed() {
            super.onConnectionFailed();
        }
    };

    private MediaControllerCompat.Callback mCallback = new MediaControllerCompat.Callback() {
        @Override
        public void onPlaybackStateChanged(PlaybackStateCompat state) {
            updatePlaybackState(state);
        }

        @Override
        public void onMetadataChanged(MediaMetadataCompat metadata) {
            updateMetadata(metadata);
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ControllerNormal:
                normal.setVisibility(View.GONE);
                shuffle.setVisibility(View.VISIBLE);
                MusicService.LOOP = false;
                MusicService.SHUFFLE = true;
                sp.edit().putBoolean("shuffle", true).commit();
                Intent intent = new Intent(MusicPlayingActivity.this, MusicService.class);
                startService(intent);
                Toast.makeText(MusicPlayingActivity.this, "随机播放", Toast.LENGTH_SHORT).show();
                break;
            case R.id.ControllerShuffle:
                shuffle.setVisibility(View.GONE);
                loop.setVisibility(View.VISIBLE);
                MusicService.LOOP = true;
                MusicService.SHUFFLE = false;
                sp.edit().putBoolean("loop", true).commit();
                sp.edit().putBoolean("shuffle", false).commit();
                Toast.makeText(MusicPlayingActivity.this, "单曲循环", Toast.LENGTH_SHORT).show();
                break;
            case R.id.ControllerLoop:
                loop.setVisibility(View.GONE);
                normal.setVisibility(View.VISIBLE);
                MusicService.LOOP = false;
                sp.edit().putBoolean("loop", false).commit();
                Toast.makeText(MusicPlayingActivity.this, "列表循环", Toast.LENGTH_SHORT).show();
                break;
            case R.id.ControllerList:
                getMusicList(musicProvider.getOrderList(), v);
                break;
        }
    }

    private void setListener() {
        controllerList.setOnClickListener(this);
        normal.setOnClickListener(this);
        loop.setOnClickListener(this);
        shuffle.setOnClickListener(this);
        preArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        controllerNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MediaControllerCompat.TransportControls controls =
                        getSupportMediaController().getTransportControls();
                controls.skipToNext();
            }
        });

        controllerPre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MediaControllerCompat.TransportControls controls =
                        getSupportMediaController().getTransportControls();
                controls.skipToPrevious();
            }
        });
        controllerPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MediaControllerCompat.TransportControls controls = getSupportMediaController().getTransportControls();
                PlaybackStateCompat state = getSupportMediaController().getPlaybackState();
                if (state == null) {
                    controls.play();
                } else {
                    switch (state.getState()) {
                        case PlaybackStateCompat.STATE_PLAYING: // fall through
                        case PlaybackStateCompat.STATE_BUFFERING:
                            controllerPlay.setImageResource(R.drawable.play_btn_style);
                            controls.pause();
                            stopSeekbarUpdate();
                            break;
                        case PlaybackStateCompat.STATE_PAUSED:
                        case PlaybackStateCompat.STATE_STOPPED:
                            controllerPlay.setImageResource(R.drawable.pause_btn_style);
                            controls.play();
                            scheduleSeekbarUpdate();
                            break;
                        default:
                    }
                }
            }
        });
        controllerSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                controllerCurrent.setText(DateUtils.formatElapsedTime(progress / 1000));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                stopSeekbarUpdate();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                getSupportMediaController().getTransportControls().seekTo(seekBar.getProgress());
                scheduleSeekbarUpdate();
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        if (mediaBrowser != null) {
            mediaBrowser.connect();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mediaBrowser != null) {
            mediaBrowser.disconnect();
        }
        if (getSupportMediaController() != null) {
            getSupportMediaController().unregisterCallback(mCallback);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        THREAD=false;
        unregisterReceiver(durationReceiver);
        stopSeekbarUpdate();
        mExecutorService.shutdown();
    }

    private void updatePlaybackState(PlaybackStateCompat state) {
        stateCompat = state;
        switch (state.getState()) {
            case PlaybackStateCompat.STATE_PLAYING:
                MyApplication.getInstance().setIsPlaying(true);
                controllerPlay.setImageResource(R.drawable.pause_btn_style);
                scheduleSeekbarUpdate();
                isStart=true;
                if (!thread.isAlive()){
                    thread.start();
                }
                break;
            case PlaybackStateCompat.STATE_PAUSED:
                MyApplication.getInstance().setIsPlaying(false);
                controllerPlay.setImageResource(R.drawable.play_btn_style);
                stopSeekbarUpdate();
                isStart=false;
                break;
            case PlaybackStateCompat.STATE_STOPPED:
                MyApplication.getInstance().setIsPlaying(false);
                controllerPlay.setImageResource(R.drawable.play_btn_style);
                stopSeekbarUpdate();
                isStart=false;
                break;
            case PlaybackStateCompat.STATE_BUFFERING:
                MyApplication.getInstance().setIsPlaying(true);
                controllerPlay.setImageResource(R.drawable.pause_btn_style);
                Intent intent = new Intent();
                intent.setAction("musicBar");
                sendBroadcast(intent);
                stopSeekbarUpdate();
                controllerDisk.setRotation(0);
                if (!thread.isAlive()) {
                    thread.start();
                }
                break;
            default:
                break;
        }
    }

    private void updateMetadata(MediaMetadataCompat metadata) {
        if (metadata != null) {
            playerName.setText(metadata.getText(MediaMetadataCompat.METADATA_KEY_TITLE));
            playerArtist.setText(metadata.getText(MediaMetadataCompat.METADATA_KEY_ARTIST));
            String duration = metadata.getString(MediaMetadataCompat.METADATA_KEY_AUTHOR).toString();
            if (!duration.equals("0")) {
                duration = String.valueOf(this.duration);
                controllerDuration.setText(DateUtils.formatElapsedTime(Long.valueOf(duration) / 1000));
                controllerSeekBar.setMax(Integer.valueOf(duration));
            }
            String ablumUrl = metadata.getString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI);
            ImageLoader.getInstance().displayImage(ablumUrl, playerImg, MyApplication.getPlayingOptions(), new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String imageUri, View view) {
                }

                @Override
                public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                }

                @Override
                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                    loadedImage = Bitmap.createScaledBitmap(loadedImage,
                            loadedImage.getWidth() / 10,
                            loadedImage.getHeight() / 10,
                            false);
                    FastBlurUtil.doBlur(loadedImage, 8, true);
                    backgroundImage.setImageBitmap(loadedImage);
                }

                @Override
                public void onLoadingCancelled(String imageUri, View view) {
                }
            });
            if (!duration.equals("0")) {
                callback.setMetaData(playerName.getText().toString(), playerArtist.getText().toString(), Integer.valueOf(duration));
            }else {
                callback.setMetaData(playerName.getText().toString(), playerArtist.getText().toString(), MyApplication.getInstance().getDuration());
            }
            if (stateCompat == null) {
                return;
            }
        }
    }

    private void updateProgress() {
        if (stateCompat == null) {
            return;
        }
        long currentPosition = stateCompat.getPosition();
        if (stateCompat.getState() != PlaybackStateCompat.STATE_PAUSED) {
            long timeDelta = SystemClock.elapsedRealtime() - stateCompat.getLastPositionUpdateTime();
            currentPosition += (int) timeDelta * stateCompat.getPlaybackSpeed();
        }
        controllerSeekBar.setProgress((int) currentPosition);
    }

    private void scheduleSeekbarUpdate() {
        stopSeekbarUpdate();
        if (!mExecutorService.isShutdown()) {
            mScheduleFuture = mExecutorService.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            updateProgress();
                        }
                    });
                }
            }, 100, 100, TimeUnit.MILLISECONDS);
        }
    }

    private Handler mHandler = new Handler();

    private void stopSeekbarUpdate() {
        if (mScheduleFuture != null) {
            mScheduleFuture.cancel(false);
        }
    }

    public static Callback callback;

    public static Callback getCallback() {
        return callback;
    }

    public static void setCallback(Callback callback) {
        MusicPlayingActivity.callback = callback;
    }

    public interface Callback {

        void setMetaData(String title, String artist, int duration);

    }

    public void getMusicList(final List<MediaMetadataCompat> metadataList, View v) {
        View view = LayoutInflater.from(this).inflate(R.layout.music_list_layout, null);
        final ListView listView = (ListView) view.findViewById(R.id.MusicListView);
        TextView num = (TextView) view.findViewById(R.id.MusicListNum);
        num.setText("(" + String.valueOf(metadataList.size()) + ")");
        adapter = new MusicListViewAdapter(metadataList, this);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MusicPlayingActivity.this, MusicService.class);
                intent.putExtra("click", true);
                intent.putExtra("musicList", true);
                intent.putExtra("position", position);
                startService(intent);
            }
        });
        PopupWindow popupWindow = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));
        popupWindow.setAnimationStyle(R.style.popupwindowanim);
        popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
    }

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            controllerDisk.setRotation(controllerDisk.getRotation() + 0.1f);
        }
    };

    private class CircleThread implements Runnable {
        @Override
        public void run() {
            while (THREAD) {
                if (isStart) {
                    handler.sendEmptyMessage(1);
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
